package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.pojo.Outward;
import com.neudu.yiyang.service.OutwardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class OutwardController {
    private static final Logger logger = LoggerFactory.getLogger(OutwardController.class);

    @Autowired
    private OutwardService outwardService;
    @Autowired
    private JSONReturn jsonReturn;

    // 查询所有外出信息
    @RequestMapping("get_all_outward")
    public String getAll(@RequestBody PageInfo pageInfo) {
        try {
            // 开启分页，设置当前页码和每页数量
            PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
            List<Outward> list = outwardService.list();
            PageInfo<Outward> pageInfoReturn = new PageInfo<>(list);
            return jsonReturn.returnSuccess(pageInfoReturn);
        } catch (Exception e) {
            logger.error("查询所有外出信息时发生异常：", e);
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("get_outwards_by")
    public String getByCondition(@RequestBody Outward outward) {
        try {
            LambdaQueryWrapper<Outward> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(!ObjectUtils.isEmpty(outward.getId()), Outward::getId, outward.getId())
                    .eq(!ObjectUtils.isEmpty(outward.getRemarks()), Outward::getRemarks, outward.getRemarks())
                    .like(!ObjectUtils.isEmpty(outward.getCustomerId()), Outward::getCustomerId, outward.getCustomerId())
                    .eq(!ObjectUtils.isEmpty(outward.getOutgoingreason()), Outward::getOutgoingreason, outward.getOutgoingreason())
                    .eq(!ObjectUtils.isEmpty(outward.getAuditperson()), Outward::getAuditperson, outward.getAuditperson());
            List<Outward> outwards = outwardService.list(queryWrapper);
            return jsonReturn.returnSuccess(outwards);
        } catch (Exception e) {
            logger.error("根据条件查询外出信息时发生异常：", e);
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("add_one_outward")
    public String addOne(@RequestBody Outward outward) {
        try {
            outwardService.save(outward);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            logger.error("添加外出登记信息时发生异常：", e);
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("getoutward_id")
    public String getById(@RequestParam("id") Integer id) {
        try {
            Outward outward = outwardService.getById(id);
            return jsonReturn.returnSuccess(outward);
        } catch (Exception e) {
            logger.error("根据ID查询外出信息时发生异常：", e);
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("modifyoutwardby_id")
    public String modifyById(@RequestBody Outward outward) {
        try {
            outwardService.updateById(outward);
            return jsonReturn.returnSuccess(outward);
        } catch (Exception e) {
            logger.error("修改外出登记信息时发生异常：", e);
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("removeoutward_by_id")
    public String removeByid(@RequestParam("id") Integer id) {
        try {
            outwardService.removeById(id);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            logger.error("删除外出登记信息时发生异常：", e);
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 检查客户是否有未回归的外出记录
    @RequestMapping("check_customer_outward_status")
    @Cacheable(value = "customerOutwardStatus", key = "#outward.customerId")
    public String checkCustomerOutwardStatus(@RequestBody Outward outward) {
        try {
            LambdaQueryWrapper<Outward> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Outward::getCustomerId, outward.getCustomerId())
                    .isNull(Outward::getActualreturntime);
            boolean hasUnreturned = outwardService.count(queryWrapper) > 0;
            return jsonReturn.returnSuccess(hasUnreturned);
        } catch (Exception e) {
            logger.error("检查客户外出状态时发生异常：", e);
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 标记外出记录为已回归
    @RequestMapping("mark_outward_returned")
    public String markOutwardReturned(@RequestBody Outward outward) {
        try {
            Outward updateOutward = new Outward();
            updateOutward.setId(outward.getId());
            updateOutward.setActualreturntime(outward.getActualreturntime());
            outwardService.updateById(updateOutward);
            // 清除缓存
            // 这里需要根据具体的缓存实现来清除对应客户的缓存
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            logger.error("标记外出记录为已回归时发生异常：", e);
            return jsonReturn.returnError(e.getMessage());
        }
    }
}